<script setup lang="ts">
import {ref, PropType, onMounted, nextTick} from 'vue'
import {ElTree} from 'element-plus'
import {RoleDetailInfor} from '@/api/baseSetting/roleManager'
import {MenusStatic} from '@/util/router'
import {MenuView} from '@/store/nav'

//是否显示
const props = defineProps({
  //角色菜单按钮功能信息
  roleDeatil: {
    type: Object as PropType<RoleDetailInfor>,
    required: true
  }
})

const emits = defineEmits(['change'])

//菜单选中
const hasMenuSeleted = ref(false)

//菜单按钮值映射
const menuTreeProps = {
  children: 'children',
  label: 'label',
  id: 'code'
}

const menu = MenusStatic.filter((item) => {
  return item.code !== 'Welcome'
})

//菜单树数据
const menuTreeData = ref<Array<MenuView>>(menu)

const menuTreeRef = ref<InstanceType<typeof ElTree>>()

//设置角色菜单按钮树勾选数据
const setRoleMenuTreeSelete = () => {
  menuTreeRef.value?.setCheckedKeys(props.roleDeatil.menuCheckedList)
  hasMenuSeleted.value = props.roleDeatil.menuCheckedList.length > 0 ? true : false
}

//获取角色菜单按钮树勾选数据
const getRoleMenuTreeSelete = (): Array<string> | undefined => {
  return menuTreeRef.value?.getCheckedKeys(true) as
    | Array<string>
    | undefined
}

//更新选中信息
const updateSelete = () => {
  emits('change', hasMenuSeleted.value, getRoleMenuTreeSelete())
}

//角色详细数据
const setRoleDetail = () => {
  setRoleMenuTreeSelete()
  nextTick(() => {
    updateSelete()
  })
}

//菜单按钮树选中变更
const onMenuChange = (_data: MenuView, obj: {checkedKeys: string[]}) => {
  hasMenuSeleted.value = obj.checkedKeys.length ? true : false
  updateSelete()
}

onMounted(() => {
  setRoleDetail()
})
</script>

<template>
  <div>
    <el-tabs type="card">
      <el-tab-pane class="rolemangaer-tabs-pane" label="页面权限">
        <el-scrollbar
          class="d-common-flex-full d-common-post-rel rolemangaer-tree__wapper"
          wrap-class="d-common-width-full d-common-post-abs"
        >
          <el-tree
            ref="menuTreeRef"
            class="d-common-width-full rolemanger-tree_con"
            node-key="code"
            show-checkbox
            highlight-current
            default-expand-all
            :data="menuTreeData"
            :props="menuTreeProps"
            @check="onMenuChange"
          />
        </el-scrollbar>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<style scoped>
.rolemangaer-tabs-pane {
  overflow: auto;
}
.rolemangaer-tree__wapper {
  height: var(--rolemangaer-tree-height);
  padding: 0;
  margin: 18px 23px;
}
</style>
